// const fs = require('fs')
const path = require('path')
const chalk = require('chalk')

const FileManagerPlugin = require('filemanager-webpack-plugin')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')

// 打包耗时
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const buildMainConfig = {
  productionSourceMap: false,
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/',
  parallel: false,
  lintOnSave: process.env.NODE_ENV !== 'production',

  devServer: {
    open: true,
    overlay: {
      warnings: true,
      errors: true,
    },
    proxy: {
      '/devApi': {
        target: 'http://192.168.22.12:9999', // 本地ip
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/devApi': '/',
        },
      },
      '/api': {
        target: 'https://wenshang.inspirestar.cn', // 测试ip
        // target: 'http://192.168.22.12:9999', // 测试ip
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': '/',
        },
      },
    },
  },

  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      config.plugins.push(new SpeedMeasurePlugin())
      config.plugins.push(new LodashModuleReplacementPlugin())
      // 是否部署到测试环境
      const isProdTest = process.env.VUE_APP_BUILD_ENV === 'test'
      // const ENV_NAME = (isProdTest && '-test') || ''
      const ENV_NAME = '-' + (process.env.VUE_APP_BUILD_ENV || 'devlop')
      // 替换 api base ip
      const baseUriPath = isProdTest ? './ipbase.test.js' : './ipbase.prod.js'

      config.plugins.push(
        new FileManagerPlugin({
          events: {
            onEnd: [
              {
                copy: [
                  {
                    source: baseUriPath,
                    destination: './dist/static/config.js',
                  },
                ],
                // 删除文件时会报错找不到文件，FileManagerPlugin内部问题，请忽略
                // delete: ['./dist/static/config.test.js', './dist/static/config.prod.js'],
                mkdir: ['./release'],
                archive: [
                  {
                    source: './dist',
                    destination: `./release/中小微企业判定监测系统-${getNowDateTimeShortStr()}${ENV_NAME}.zip`,
                  },
                ],
              },
            ],
          },
        })
      )
    }
  },
  chainWebpack: config => {
    // 多页面时，去掉该配置（html）
    config.plugin('html').tap(args => {
      args[0].title = '中小微企业判定监测系统'
      return args
    })

    // 配置解析别名
    setAlias(config)

    config.optimization.splitChunks({
      chunks: 'all',
      minSize: 100000,
      maxAsyncRequests: 10,
      maxInitialRequests: 6,
      automaticNameDelimiter: '~',
      name: true,
      cacheGroups: {
        common: {
          name: 'chunk-common',
          chunks: 'initial',
          priority: 2,
          reuseExistingChunk: true,
          enforce: true,
        },
        // 抽离node_modules下的库为一个chunk
        tinymce: {
          name: 'chunk-tinymce',
          test: /[\\/]node_modules[\\/]tinymce[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        xlxs: {
          name: 'chunk-xlsx',
          test: /[\\/]node_modules[\\/]xlsx[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        echarts: {
          name: 'chunk-echarts',
          test: /[\\/]node_modules[\\/]echarts[\\/]/,
          priority: 4,
          reuseExistingChunk: true,
          enforce: true,
        },
        zrender: {
          name: 'chunk-echarts',
          test: /[\\/]node_modules[\\/]zrender[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        vxeTable: {
          name: 'chunk-vxe-table',
          test: /[\\/]node_modules[\\/]vxe-table[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        elementUI: {
          name: 'chunk-element-ui',
          test: /[\\/]node_modules[\\/]element-ui[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        baiduMap: {
          name: 'chunk-baidu-map',
          test: /[\\/]node_modules[\\/]vue-baidu-map[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        pdfjs: {
          name: 'chunk-pdfjs',
          test: /[\\/]node_modules[\\/]pdfjs-dist[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        antv: {
          name: 'chunk-antv',
          test: /[\\/]node_modules[\\/]@antv[\\/]/,
          priority: 3,
          reuseExistingChunk: true,
          enforce: true,
        },
        vendors: {
          name: 'chunk-vendors',
          test: /[\\/]node_modules[\\/]/,
          priority: 1,
          reuseExistingChunk: true,
          enforce: true,
        },
      },
    })

    // md 文档
    config.module
      .rule('md')
      .test(/\.md$/)
      .use('vue-loader')
      .loader('vue-loader')
      .end()
      .use('vue-markdown-loader')
      .loader('vue-markdown-loader/lib/markdown-compiler')
      .options({
        raw: true,
      })
  },
  css: {
    loaderOptions: {
      scss: {
        additionalData: '@import "@styles/var.scss"; @import "@styles/mixin.scss";',
      },
    },
  },
  // 解决ie 下 Number 对象方法兼容性问题
  // transpileDependencies: ['element-ui'],
}

const isBuildComplaintClient = process.env.VUE_APP_BUILD_PART === 'complaint'

process.env.NODE_ENV === 'production' &&
  console.log(chalk.green('BUILD PART >>> ', (isBuildComplaintClient && '2: complaint clinet') || '1: main'))

// const config = isBuildComplaintClient ? buildComplaintConfig : buildMainConfig
const config = buildMainConfig

module.exports = config

function setAlias(config) {
  config.resolve.alias
    .set('@libs', resolve('./src/libs'))
    .set('@styles', resolve('./src/assets/styles'))
    .set('@font', resolve('./src/assets/font'))
    .set('@com', resolve('./src/components'))
    .set('@bcom', resolve('./src/businessComponents'))
    .set('@views', resolve('./src/views'))
    .set('@api', resolve('./src/apis'))
    .set('@apis', resolve('./src/apis/modules'))
    .set('@utility', resolve('./src/utility'))
    .set('@images', resolve('./src/assets/images'))
    .set('@controller', resolve('./src/controller'))
    .set('@mock', resolve('./src/mock'))
    .set('@directives', resolve('./src/directives'))
    .set('@layouts', resolve('./src/layouts'))
    .set('@pages', resolve('./src/pages'))
}

function dateToTimeStr(date) {
  const yyyy = date.getFullYear()
  const mth = dateNum2Str(date.getMonth() + 1)
  const dd = dateNum2Str(date.getDate())
  const hh = dateNum2Str(date.getHours())
  const mm = dateNum2Str(date.getMinutes())
  const ss = dateNum2Str(date.getSeconds())
  return `${yyyy}-${mth}-${dd} ${hh}:${mm}:${ss}`
}
// 返回当前时间标准字符串 yyyyMMddhhmmss 20180514153320
function getNowDateTimeShortStr() {
  return dateToTimeStr(new Date()).replace(/[\s|\s*-\s*|:]/g, '')
}

function dateNum2Str(num) {
  if (num < 10) {
    return '0' + num
  } else {
    return num + ''
  }
}
